package org.test.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by Hy on 2018/7/6.
 * CGLib动态代理
 */
public class CGlibProxy implements MethodInterceptor {
    private static CGlibProxy instance=new CGlibProxy();

    private CGlibProxy() {
    }
    public static CGlibProxy getInstance(){
        return instance;
    }
    public <T> T getProxy(Class<T> cls){
        return (T) Enhancer.create(cls,this);
    }
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        before();
        Object result = methodProxy.invokeSuper(obj, args);
        after();
        return result;
    }
    private void before(){
        System.out.println("Before");
    }
    private void after(){
        System.out.println("After");
    }

    public static void main(String[] args) {
        Hello helloProxy = CGlibProxy.getInstance().getProxy(HelloImpl.class);
        helloProxy.say("Jack");
    }
}
